#coding=utf-8
from django.contrib import admin

from django.core.exceptions import MultipleObjectsReturned
from PublicTool import HttpWrite
from PublicTool.BaseAdmin import UserModelAdmin

import models

from travel.TravelData.models import PositionType

__author__ = 'czq'



#
class RidePositionAdmin(UserModelAdmin):

    def get_readonly_fields(self, request, obj=None):
        return ('longitude','latitude','address',)
    def response_change(self, request, obj):
        return HttpWrite.infoSuccess('<script type="text/javascript">alert("保存成功！");self.close()</script>')

    fields = ('city','arriveTime','departureTime','longitude','latitude','address','content',)


admin.site.register(models.RidePosition, RidePositionAdmin)

class RidePositionInline(admin.TabularInline):

    #def get_readonly_fields(self, request, obj=None):
    #    return ('longitude','latitude',)
    model = models.RidePosition
    fields = ('longitude','latitude','address','positionType','arriveTime','departureTime','rank',)

    extra = 3
    ordering = ['rank']




class RideLineAdmin(UserModelAdmin):

    def save_formset(self, request, form, formset, change):
        super(RideLineAdmin,self).save_formset(request,form,formset,change)

        line=form.save(commit=False)

        #line.startPosition=models.RidePosition.objects.get(travelLine=line,positionType=PositionType.objects.get(type=0)).id

        try:
            line.startPosition=models.RidePosition.objects.get(travelLine=line,positionType=PositionType.objects.get(type=0)).id
        except MultipleObjectsReturned:
            raise Exception,u"两个起点"
        except:
            pass
        try:
            line.endPosition=models.RidePosition.objects.get(travelLine=line,positionType=PositionType.objects.get(type=2)).id
        except MultipleObjectsReturned:
            raise Exception,u"两个终点"
        except:
            pass
        line.save()

    fields = ('name','content','lineType','startTime','endTime',)
    inlines = [RidePositionInline,]

admin.site.register(models.RideLine, RideLineAdmin)
#






